import React, { useCallback, useEffect, useState } from 'react';
import { Modal, Card, Row, Col, Tree, Select, Button, Input } from 'antd';

import _ from 'lodash';

import { PlusOutlined, DeleteOutlined } from '@ant-design/icons';

import { IArrayTable } from './type';
import BuildTitle from '@/components/BuildTitle';
import ScrollBarLayout from '@/components/ScrollBarLayout';

import cls from 'classnames';
import './styles.less';

export const NodeArrayTable: React.FC<IArrayTable> = ({
  title,
  onClose,
  tableData,
  onFormChange,
  defaultValue,
}) => {
  const className = 'class' + parseInt(String(Math.random() * 1000000));
  const modalTitle = (
    <BuildTitle title={title ?? '弹窗'} className={className} />
  );

  const [treeData, setTreeData] = useState<any[]>([]);
  const [selectNode, setSelect] = useState<Record<string, any> | null>(null);
  const [fileData, setFile] = useState<any[]>([]);

  useEffect(() => {
    loopTree();
    if (defaultValue) {
      setFile(defaultValue);
    }
  }, [tableData]);

  const loopTree = useCallback(() => {
    let newTree = tableData?.map((item) => {
      return {
        ...item,
        title: item?.label,
        key: item?.mark,
      };
    });
    setTreeData(newTree);
  }, [tableData]);

  const onSelectTarget = useCallback(
    (selectedKeys: any, e: any) => {
      let [selectNodes] = e?.selectedNodes;
      setSelect(selectNodes);
    },
    [tableData],
  );

  const onAppendKey = useCallback(() => {
    let treeKeys: any = {};

    tableData?.forEach((item) => {
      treeKeys[item?.value] = '';
    });

    let newFileData = _.cloneDeep(fileData);

    newFileData.push({
      ...treeKeys,
      id: '',
      seq: newFileData.length + 1,
      mark: Math.random(),
    });

    setFile(newFileData);
  }, [fileData, tableData]);

  const onFileChange = useCallback(
    (valueKey: string, value: any, targetId: any) => {
      let newFile = fileData.map((item) => {
        if (item?.mark === targetId) {
          return {
            ...item,
            [valueKey]: value,
          };
        }

        return {
          ...item,
        };
      });

      setFile(newFile);
    },
    [fileData],
  );

  const onDelete = useCallback(
    (index) => {
      let newFile = _.cloneDeep(fileData);

      newFile.splice(index, 1);

      setFile(newFile);
    },
    [fileData],
  );

  const onOk = () => {
    onFormChange(fileData);
    onClose();
  };

  return (
    <Modal
      title={modalTitle}
      className={className}
      onCancel={onClose}
      open={true}
      width={1000}
      bodyStyle={{ padding: '.75rem' }}
      onOk={onOk}
    >
      <Row style={{ height: '100%' }}>
        <Col span={8}>
          <Card
            title="字段设置"
            style={{ height: '100%' }}
            size={'small'}
            type={'inner'}
            bodyStyle={{ height: '20rem' }}
          >
            <Tree
              showLine={{
                showLeafIcon: false,
              }}
              blockNode
              treeData={treeData}
              onSelect={onSelectTarget}
            />
          </Card>
        </Col>
        <Col span={16}>
          <Card
            title="键值设置"
            style={{ height: '100%' }}
            size={'small'}
            type={'inner'}
            className={cls('array-card')}
            bodyStyle={{ height: '20rem', padding: 0 }}
            extra={
              <>
                <Button
                  size={'small'}
                  icon={<PlusOutlined />}
                  onClick={onAppendKey}
                >
                  新增键值
                </Button>
                &nbsp;
                <Button
                  size={'small'}
                  icon={<DeleteOutlined />}
                  onClick={() => {
                    setFile([]);
                  }}
                >
                  清空
                </Button>
              </>
            }
          >
            <ScrollBarLayout style={{ padding: '.5rem' }}>
              {fileData && fileData.length > 0 ? (
                <>
                  <Row
                    gutter={[12, 12]}
                    style={{
                      display:
                        selectNode?.valueType === 'Input' ? 'flex' : 'none',
                    }}
                  >
                    {fileData?.map((item, index) => {
                      return (
                        <Col
                          span={12}
                          key={index}
                          style={{ display: 'flex', alignItems: 'center' }}
                        >
                          <Input
                            placeholder={'请输入' + selectNode?.label}
                            onChange={(e) => {
                              let value = e?.target?.value;
                              let valueKey = selectNode?.value;
                              let targetId = item?.mark;
                              onFileChange(valueKey, value, targetId);
                            }}
                            value={item?.[selectNode?.value]}
                          />
                          <Button
                            size={'small'}
                            danger={true}
                            icon={
                              <DeleteOutlined
                                onClick={() => {
                                  onDelete(index);
                                }}
                              />
                            }
                            type={'text'}
                          ></Button>
                        </Col>
                      );
                    })}
                  </Row>
                  <Row
                    gutter={[12, 12]}
                    style={{
                      display:
                        selectNode?.valueType === 'Select' ? 'flex' : 'none',
                    }}
                  >
                    {fileData?.map((item, index) => {
                      return (
                        <Col
                          span={12}
                          key={index}
                          style={{ display: 'flex', alignItems: 'center' }}
                        >
                          <Select
                            style={{ width: '100%', marginRight: '.5rem' }}
                            placeholder={'请选择' + selectNode?.label}
                            onChange={(e) => {
                              let value = e;
                              let valueKey = selectNode?.value;
                              let targetId = item?.mark;
                              onFileChange(valueKey, value, targetId);
                            }}
                            value={item?.[selectNode?.value]}
                          >
                            {selectNode?.optionList?.map(
                              (item: any, index: number) => {
                                return (
                                  <Select.Option
                                    value={item?.value}
                                    key={index}
                                  >
                                    {item?.label}
                                  </Select.Option>
                                );
                              },
                            )}
                          </Select>
                          <Button
                            size={'small'}
                            danger={true}
                            icon={
                              <DeleteOutlined
                                onClick={() => {
                                  onDelete(index);
                                }}
                              />
                            }
                            type={'text'}
                          ></Button>
                        </Col>
                      );
                    })}
                  </Row>
                </>
              ) : (
                <></>
              )}
            </ScrollBarLayout>
          </Card>
        </Col>
      </Row>
    </Modal>
  );
};
